package xyz.chaobei.mongo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import xyz.chaobei.mongo.model.OrgUser;
import xyz.chaobei.mongo.repository.OrgUserRepository;

@SpringBootApplication
@EnableMongoRepositories
public class Application implements CommandLineRunner {

    @Autowired
    private OrgUserRepository orgUserRepository;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        // delete
        orgUserRepository.deleteAll();
        System.out.println("deleteAll...");

        OrgUser user = new OrgUser();
        user.setUsername("mrc");
        user.setPassword("123456");

        // save
        OrgUser defaultUser = orgUserRepository.insert(user);
        System.out.println("defaultUser:" + defaultUser);

        for (int i = 0; i < 10; i++) {

            OrgUser orgUser = new OrgUser();
            orgUser.setPassword("pass" + i);
            orgUser.setUsername("user" + i);

            OrgUser dbUser2 = orgUserRepository.insert(orgUser);
            System.out.println(i + ":" + dbUser2);
        }

        // query
        OrgUser search = orgUserRepository.findOrgUserByUsername("mrc");
        System.out.println("search:" + search);

        defaultUser.setUsername("defaultUser");
        defaultUser.setPassword("defaultUser123456");

        // update
        OrgUser newUser = orgUserRepository.save(defaultUser);
        System.out.println("newUser:" + newUser);
    }
}
